﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SerialPrint
{
    public partial class MainForm : Form
    {
        string document = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"><html><head><title>序列号</title>{0}</head><body>{1}</body></html>";
        string style = "<style type=\"text/css\">html, body { margin: 0; padding: 0; line-height: 200%; font-size: 14px; }table { width: 200mm; margin: 0 auto; border-spacing: 2.5mm 0; }td { width: 50%; padding: 4.5mm; height: 48mm; }@media screen {.table { border: 1px solid #000; margin-top: 5mm; margin-bottom: 5mm; }}</style>";

        public MainForm()
        {
            InitializeComponent();
            //wbPrint.Url = new Uri(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "print.html"));
        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            if (ofdFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                tbFile.Text = ofdFile.FileName;
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            wbPrint.ShowPrintPreviewDialog();
        }

        private void btnPreview_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbFile.Text) || string.IsNullOrWhiteSpace(tbContent.Text))
            {
                return;
            }

            var lines = System.Net.WebUtility.HtmlEncode(tbContent.Text + "\r\n注 册 码：").Split(new char[] { '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
            var single ="<td>"+ string.Join("<br />", lines) + "{1}</td>";
            StringBuilder html = new StringBuilder();
            var serials = File.ReadAllLines(tbFile.Text);
            for (int i = 0; i < serials.Length; i++)
            {
                string css = "item_left";
                if ((i + 1) % 2 == 0)
                {
                    css = "item_right";
                }
                else
                {
                    html.Append("<tr>");
                }
                html.AppendFormat(single, css, serials[i].Trim());
                if ((i + 1) % 2 == 0)
                {
                    html.Append("</tr>");
                }

            }
            if (serials.Length % 2 != 0)
            {
                html.Append("</tr>");
            }
            //wbPrint.Document.Body.InnerHtml = string.Format(body, html.ToString());
            string content = string.Format(document, style, "<table>" + html.ToString() + "</table>");
            wbPrint.DocumentText = content;
            File.WriteAllText(@"d:\test.html", content);
        }
    }
}
